package com.infore.airsupervise.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.TextView;

import com.beardedhen.androidbootstrap.AwesomeTextView;
import com.beardedhen.androidbootstrap.font.FontAwesome;
import com.bigkoo.pickerview.TimePickerView;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.formatter.DefaultValueFormatter;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.infore.airsupervise.R;
import com.infore.airsupervise.adapter.PointAnalyzeTableAdapter;
import com.infore.airsupervise.app.Constants;
import com.infore.airsupervise.bean.MenuE;
import com.infore.airsupervise.utils.DateUtil;
import com.infore.airsupervise.utils.JumpUtil;
import com.infore.airsupervise.utils.ToastUtil;
import com.inqbarna.tablefixheaders.TableFixHeaders;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 预警统计
 * Created by xiaotao on 2017/8/9.
 */

public class AlarmStatisticActivity extends BaseActivity {

    @BindView(R.id.titlebar_title)
    TextView title;
    @BindView(R.id.titlebar_right_menu)
    AwesomeTextView rightMenu;
    @BindView(R.id.titlebar_offline_menu)
    AwesomeTextView offlineMenu;
    @BindView(R.id.tv_startTime)
    TextView tvStartTime;
    @BindView(R.id.tv_endTime)
    TextView tvEndTime;
    @BindView(R.id.scroll_table)
    TableFixHeaders scrollTable;
    @BindView(R.id.barChart)
    BarChart mChart;

    private boolean isShowChart = true;
    private String startTime;
    private String endTime;

    private boolean[] showType = {true,true,true,true,false,false};
    private TimePickerView timePickerView;
    private TextView tvTitle;


    private List<String> xAixLabel = new ArrayList<>();
    private int [] colors = {R.color.google_blue,R.color.google_green,R.color.google_red};

    private PointAnalyzeTableAdapter tableAdapter = null;
    private String[] topTitle;
    private String[] leftTitle;
    private String[][] tatbleData;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_statistic_alarm);
        ButterKnife.bind(this);
        Intent it =getIntent();
        if(it != null) {
            MenuE menuE = (MenuE) it.getSerializableExtra(Constants.INTENT_OBJ_KEY);
            if (null != menuE) {
                //titleBar
                title.setText(menuE.getTitle());
            }
        }
        initView();
    }


    private void initView(){
        //表格
        tableAdapter = new PointAnalyzeTableAdapter(ctx,topTitle,leftTitle,tatbleData);
        scrollTable.setAdapter(tableAdapter);
        //时间
        startTime = DateUtil.getStringByOffset(Calendar.getInstance().getTime(),DateUtil.FORMAT_DATE_HOUR,Calendar.HOUR_OF_DAY,-1);
        endTime = DateUtil.getCurrentDateStr(DateUtil.FORMAT_DATE_HOUR);
        tvStartTime.setText(startTime);
        tvEndTime.setText(endTime);
        //图表
        initChart();

    }

    /**
     * 初始化统计图
     */
    private void initChart(){
        mChart.getDescription().setEnabled(false);

        // scaling can now only be done on x- and y-axis separately
        mChart.setPinchZoom(false);
        mChart.setDrawBarShadow(false);
        mChart.setDrawGridBackground(false);
        mChart.setScaleYEnabled(false);


        Legend l = mChart.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
        l.setOrientation(Legend.LegendOrientation.VERTICAL);
        l.setDrawInside(true);
        l.setTextSize(8f);

        XAxis xAxis = mChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setGranularity(1f);
        xAxis.setCenterAxisLabels(true);
        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                int index = (int) value;
                if(index>=0 && index <xAixLabel.size()){
                    return xAixLabel.get(index);
                }else {
                    return "";
                }
            }
        });
        YAxis leftAxis = mChart.getAxisLeft();
        leftAxis.setDrawGridLines(false);
        leftAxis.setSpaceTop(35f);
        leftAxis.setAxisMinimum(0f);
        leftAxis.setGranularityEnabled(true);
        //右Y轴
       mChart.getAxisRight().setEnabled(false);
        setChartData();
    }

    private void setChartData(){
        float groupSpace = 0.08f;
        float barSpace = 0.12f/3; // x4 DataSet
        float barWidth = 0.8f/3; // x4 DataSet
        // (0.2 + 0.03) * 4 + 0.08 = 1.00 -> interval per "group"
        xAixLabel.clear();
        leftTitle = new String[6];
        topTitle = new String[3];
        tatbleData = new String[6][3];
        for(int j = 0 ;j<6 ;j++){
            xAixLabel.add("实验站"+(j+1));
            leftTitle[j] = "实验站"+(j+1);
        }
        List<List<BarEntry>> datas = new ArrayList<>();
        for(int i = 0 ; i<3 ;i++){
            topTitle[i]= "超国控点"+(100+50*i)+"%次数";
            List<BarEntry> yVals = new ArrayList<>();
            for(int j = 0 ;j<6 ;j++){
                int value = (int) (Math.random()*50);
                yVals.add(new BarEntry(j ,value));
                tatbleData[j][i] = value+"";
            }
            datas.add(yVals);
        }

        int xCount = 6;
        BarData  barData = new BarData();
        for(int i = 0 ;i < datas.size() ;i++){
            BarDataSet dataSet = new BarDataSet(datas.get(i),"超国控点"+(100+50*i)+"%次数");

            if(i==0){
                dataSet.setColor(ContextCompat.getColor(ctx,colors[1]));
            }else if(i==1) {
                dataSet.setColor(ContextCompat.getColor(ctx,colors[2]));
            }else {
                dataSet.setColor(ContextCompat.getColor(ctx,colors[0]));
            }
            barData.addDataSet(dataSet);
        }
        barData.setValueFormatter(new DefaultValueFormatter(0));
        mChart.setData(barData);
        // specify the width each bar should have
        mChart.getBarData().setBarWidth(barWidth);

        // restrict the x-axis range
        mChart.getXAxis().setAxisMinimum(0);

        // barData.getGroupWith(...) is a helper that calculates the width each group needs based on the provided parameters
        mChart.getXAxis().setAxisMaximum(0 + mChart.getBarData().getGroupWidth(groupSpace, barSpace) * xCount);
        mChart.groupBars(0, groupSpace, barSpace);
        mChart.animateY(1000);
        mChart.invalidate();
        tableAdapter.updata(topTitle,leftTitle,tatbleData);
    }

    /**
     * 初始化时间选择器
     */
    private void initTimePicker(){
        Calendar endSelectedDate = Calendar.getInstance();
        timePickerView = new TimePickerView.Builder(ctx, timeSelectListener)
                .setTitleText("")
                .setLabel("年", "月", "日", "点", "分", "秒")
                .setType(showType)
                .isCenterLabel(false)
                .setDividerColor(Color.DKGRAY)
                .setContentSize(18)
                .setRangDate(null, endSelectedDate)
                .setDate(endSelectedDate)
                .setDecorView(null)
                .build();
        tvTitle = (TextView) timePickerView.findViewById(com.bigkoo.pickerview.R.id.tvTitle);
    }




    /**
     * 点击事件
     * @param view
     */
    @OnClick({R.id.titlebar_left_menu, R.id.titlebar_right_menu, R.id.titlebar_offline_menu, R.id.tv_startTime, R.id.tv_endTime})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.titlebar_left_menu:
                finish();
                break;
            case R.id.titlebar_right_menu:
                isShowChart = !isShowChart;
                if(isShowChart){
                    //图标
                    rightMenu.setFontAwesomeIcon(FontAwesome.FA_BAR_CHART);
                    scrollTable.setVisibility(View.INVISIBLE);
                    mChart.setVisibility(View.VISIBLE);
                }else {
                    //表格
                    rightMenu.setFontAwesomeIcon(FontAwesome.FA_TABLE);
                    tableAdapter.notifyDataSetChanged();
                    scrollTable.setVisibility(View.VISIBLE);
                    mChart.setVisibility(View.INVISIBLE);
                }
                break;
            case R.id.titlebar_offline_menu:
                JumpUtil.jumpFromTo(ctx,OfflineStatisticActivity.class);
                break;
            case R.id.tv_startTime:
            case R.id.tv_endTime:
                if(timePickerView == null ){
                    initTimePicker();
                }
                timePickerView.show(view);
                tvTitle.setText(view.getId() == R.id.tv_startTime ? "开始时间":"结束时间");
                break;
        }
    }

    /**
     * 时间选择回调
     */
    private TimePickerView.OnTimeSelectListener timeSelectListener = new TimePickerView.OnTimeSelectListener() {
        @Override
        public void onTimeSelect(Date date, View v) {
            Calendar selector = Calendar.getInstance();
            Calendar endCalendar = Calendar.getInstance();
            selector.setTime(date);
            if (endCalendar.compareTo(selector) != 1) {
                ToastUtil.showShort(ctx, "不能超过当前日期");
                return;
            }
            switch (v.getId()){
                case R.id.tv_startTime:
                    startTime =  DateUtil.getStringByFormat(date,DateUtil.FORMAT_DATE_HOUR);
                    tvStartTime.setText(startTime);
                    break;
                case R.id.tv_endTime:
                    endTime = DateUtil.getStringByFormat(date,DateUtil.FORMAT_DATE_HOUR);
                    tvEndTime.setText(endTime);
                    setChartData();

                    break;
            }
        }
    };

}
